/**
 * axios请求封装
 */
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/store";
import router from "@/router";

// 创建axios实例
const service = axios.create({
  baseURL: "http://localhost:3000", // 接口基础路径，直接设置为我们的后端服务地址
  timeout: 15000, // 请求超时时间
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    // 如果有token，带上token
    if (userStore.token) {
      config.headers["Authorization"] = `Bearer ${userStore.token}`;
    }
    return config;
  },
  (error) => {
    console.error("请求错误", error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;

    // 如果后端返回的接口结构是 { code, data, message }，则可以按如下处理
    // 根据实际接口调整
    if (res.code !== 0 && res.code !== 200) {
      ElMessage({
        message: res.message || "系统错误",
        type: "error",
        duration: 5 * 1000,
      });

      // 如果是未授权，跳转到登录页
      if (res.code === 401) {
        // 确认退出
        ElMessageBox.confirm("您的登录已过期，请重新登录", "登录提示", {
          confirmButtonText: "重新登录",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          const userStore = useUserStore();
          userStore.logout();
          router.push(`/login?redirect=${router.currentRoute.value.fullPath}`);
        });
      }

      return Promise.reject(new Error(res.message || "系统错误"));
    } else {
      return res;
    }
  },
  (error) => {
    // 处理网络错误
    let message = "请求错误";
    if (error.response) {
      switch (error.response.status) {
        case 400:
          message = "请求错误";
          break;
        case 401:
          message = "未授权，请登录";
          // 清除token并跳转登录页
          const userStore = useUserStore();
          userStore.logout();
          router.push(`/login?redirect=${router.currentRoute.value.fullPath}`);
          break;
        case 403:
          message = "拒绝访问";
          break;
        case 404:
          message = `请求地址错误: ${error.response.config.url}`;
          break;
        case 408:
          message = "请求超时";
          break;
        case 500:
          message = "服务器内部错误";
          break;
        case 501:
          message = "服务未实现";
          break;
        case 502:
          message = "网关错误";
          break;
        case 503:
          message = "服务不可用";
          break;
        case 504:
          message = "网关超时";
          break;
        case 505:
          message = "HTTP版本不受支持";
          break;
        default:
          message = `请求失败: ${error.response.status}`;
      }
    } else if (error.request) {
      message = "服务器未响应";
    } else {
      message = "请求配置错误";
    }

    ElMessage({
      message,
      type: "error",
      duration: 5 * 1000,
    });

    return Promise.reject(error);
  }
);

export default service;
